//
//  VideoController.m
//  SNS
//
//  Created by  on 11-12-12.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "VideoController.h"
#import "SinaManager.h"
#import "MBProgressHUD.h"
#import "VideoCell.h"

@interface VideoController (Private)

- (void)refresh;
- (void)loadMore;

@end

@implementation VideoController

@synthesize videoDatas;
@synthesize loadingPage;
@synthesize webViewController;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc {
    [videoDatas release];
    [webViewController release];
    
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"视频";

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.videoDatas = [NSMutableArray array];
    
//    [self refresh];
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.videoDatas count] + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[VideoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    if ([self.videoDatas count] == 0) {
        
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        cell.textLabel.textColor = [UIColor blueColor];
        cell.textLabel.text = @"下拉刷新";
        
    }
    else if ([self.videoDatas count] != 0 && [indexPath row] == [self.videoDatas count]) {
        
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        cell.textLabel.textColor = [UIColor blueColor];
        cell.textLabel.text = @"点击载入更多...";
    }
    else {

        NSDictionary *videoData = [self.videoDatas objectAtIndex:[indexPath row]];
        ((VideoCell *)cell).text.text = [videoData objectForKey:@"text"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.videoDatas count] == 0) {
        return;
    }
    else if ([self.videoDatas count] != 0 && [indexPath row] == [self.videoDatas count]) {
        [self loadMore];
        
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.textLabel.text = @"正在载入";
        
    }
    else {
        NSDictionary *videoData = [self.videoDatas objectAtIndex:[indexPath row]];
        NSString *videoURL = [videoData objectForKey:@"videoURL"];
        NSLog(@"%@", [videoData objectForKey:@"videoURL"]);
        
        self.webViewController = [[[UIViewController alloc] init] autorelease];
        self.webViewController.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"返回"
                                                                                                    style:UIBarButtonItemStylePlain
                                                                                                   target:self
                                                                                                   action:@selector(closeWebView)] autorelease];
        UIActivityIndicatorView *indicator = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease];
        [indicator startAnimating];
        self.webViewController.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:indicator] autorelease];
        
        UIWebView *webView = [[UIWebView alloc] initWithFrame:self.webViewController.view.bounds];
        webView.scalesPageToFit = YES;
        [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:videoURL]]];
        webView.delegate = self;
        self.webViewController.view = webView;
        self.webViewController.title = @"载入中...";
        
        UINavigationController *navigation = [[[UINavigationController alloc] initWithRootViewController:self.webViewController] autorelease];
        navigation.navigationBar.barStyle = UIBarStyleBlack;
        
        [self presentModalViewController:navigation animated:YES];
    }    
}

- (void)closeWebView {
    [self.webViewController dismissModalViewControllerAnimated:YES];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    self.webViewController.title = @"";
    self.webViewController.navigationItem.rightBarButtonItem = nil;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    self.webViewController.title = @"载入失败";
    self.webViewController.navigationItem.rightBarButtonItem = nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.videoDatas count] == 0) {
        return 50;
    }
    else if ([self.videoDatas count] != 0 && [indexPath row] == [self.videoDatas count]) {
        return 50;
    }
    else {
        NSDictionary *videoData = [self.videoDatas objectAtIndex:[indexPath row]];
        NSString *text = [videoData objectForKey:@"text"];
        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:14]
                       constrainedToSize:CGSizeMake(280, MAXFLOAT)];
        return size.height + 20;
    }
}

#pragma mark - Private 

- (void)refresh {
    self.loadingPage = 1;
    [self.videoDatas removeAllObjects];
    
    [[SinaManager sharedManager] getVideoTimelineWithPage:self.loadingPage
                                                 delegate:self
                                           finishCallback:@selector(getVideoDataFinish:)
                                             failCallback:@selector(getVideoDataFail:)];
}

- (void)loadMore {
    self.loadingPage++;
    
    [[SinaManager sharedManager] getVideoTimelineWithPage:self.loadingPage
                                                 delegate:self
                                           finishCallback:@selector(getVideoDataFinish:)
                                             failCallback:@selector(getVideoDataFail:)];
}

#pragma mark - get video data callback

- (void)getVideoDataFinish:(id)result {
    NSDictionary *resultDic = (NSDictionary *)result;
    
    NSMutableArray *tempArray = [NSMutableArray array];
    
    for (NSDictionary *weibo in resultDic) {
        if ([weibo objectForKey:@"retweeted_status"] != nil) {
            NSDictionary *retweeted = [weibo objectForKey:@"retweeted_status"];
            NSString *text = [retweeted objectForKey:@"text"];
            
            for (int i = 0; i != text.length - 12; i++) {
                NSRange range = NSMakeRange(i, 12);
                NSString *subString = [text substringWithRange:range];
                if ([subString isEqualToString:@"http://t.cn/"]) {
                    NSRange urlRange = NSMakeRange(i, 18);
                    if (text.length >= i + 18) {
                        NSString *videoURL = [text substringWithRange:urlRange];
                        
                        NSMutableString *noURLText = [NSMutableString string];
                        [noURLText setString:text];
                        [noURLText deleteCharactersInRange:urlRange];
                        
                        NSMutableDictionary *weiboData = [NSMutableDictionary dictionary];
                        [weiboData setObject:noURLText forKey:@"text"];
                        [weiboData setObject:videoURL forKey:@"videoURL"];
                        [tempArray addObject:weiboData];
                        break;
                    } 
                }
            }
        }
        else {
            NSString *text = [weibo objectForKey:@"text"];
            
            for (int i = 0; i != text.length - 12; i++) {
                NSRange range = NSMakeRange(i, 12);
                NSString *subString = [text substringWithRange:range];
                if ([subString isEqualToString:@"http://t.cn/"]) {
                    NSRange urlRange = NSMakeRange(i, 18);
                    if (text.length >= i + 18) {
                        NSString *videoURL = [text substringWithRange:urlRange];
                        
                        NSMutableString *noURLText = [NSMutableString string];
                        [noURLText setString:text];
                        [noURLText deleteCharactersInRange:urlRange];
                        
                        NSMutableDictionary *weiboData = [NSMutableDictionary dictionary];
                        [weiboData setObject:noURLText forKey:@"text"];
                        [weiboData setObject:videoURL forKey:@"videoURL"];
                        [tempArray addObject:weiboData];
                        break;
                    }
                }
            }
        }

    }
    
    [self.videoDatas addObjectsFromArray:tempArray];
    
    [self.tableView reloadData];
    
    [self stopLoading];
}

- (void)getVideoDataFail:(NSString *)errorInfo {
    [self stopLoading];
}

@end
